const Router = require('koa-router')
const send = require('koa-send')
const path = require('path')
const archiver = require('archiver')
const fs = require('fs')

const basePath = path.join('F:/', 'directory');
const tempPath = path.join('F:/', 'directory_temp');

const {
  getChildrenList
} = require('../utils/handle');

const router = new Router({
  prefix: '/download'
})

router.get('/faststart/filelist', async (ctx) => {
  const {
    fileDir
  } = ctx.query;
  let result = await getChildrenList(basePath, fileDir, true)
  ctx.app.emit('success', {
    data: result,
  }, ctx)
})

router.get('/faststart/fileload', async (ctx) => {
  const {
    fileDir
  } = ctx.query;
  // const basePath = path.join(__dirname, '../assets/file/fastStart');
  // const tempPath = path.join(__dirname, '../assets/file/temp');

  const fileName = fileDir + '.zip';
  //文件输出流
  const output = fs.createWriteStream(tempPath + '/' + fileName);
  const archive = archiver('zip', {
    zlib: {
      level: 9
    }
  });
  //通过管道方法将输出流存档到文件
  archive.pipe(output);
  //添加整个文件夹到压缩包
  archive.directory(basePath + '/' + fileDir)
  //完成归档
  await archive.finalize();

  ctx.attachment(fileName);
  // 文件输出流结束
  output.on('close', function () {
    console.log(`总共 ${archive.pointer()} 字节`)
    console.log('archiver完成文件的归档，文件输出流描述符已关闭')
  })
  // 数据源是否耗尽
  output.on('end', function () {
    console.log('数据源已耗尽')
  })
  // 存档警告
  archive.on('warning', function (err) {
    if (err.code === 'ENOENT') {
      console.warn('stat故障和其他非阻塞错误')
    } else {
      throw err
    }
  })
  // 存档出错
  archive.on('error', function (err) {
    throw err
  });
  try {
    await send(ctx, fileName, {
      root: tempPath
    });
  } catch (e) {
    ctx.throw(new Error('文件不存在'), 404)
  }
});

module.exports = router;
